package handler

import (
	"fmt"
	"net/http"
	"os"
	"path/filepath"

	"github.com/gin-gonic/gin"
	"github.com/user/go-capcut/internal/draft"
	"github.com/user/go-capcut/internal/util"
)

// SaveDraftRequest 保存草稿请求
type SaveDraftRequest struct {
	DraftID string `form:"draft_id" binding:"required"`
}

// SaveDraftResponse 保存草稿响应
type SaveDraftResponse struct {
	DraftID  string `json:"draft_id"`
	DraftURL string `json:"draft_url"`
}

// SaveDraftHandler 保存草稿处理函数
func (h *Handler) SaveDraftHandler(c *gin.Context) {
	// 解析请求
	var req SaveDraftRequest
	if err := c.ShouldBindQuery(&req); err != nil {
		Error(c, http.StatusBadRequest, "Invalid request parameters")
		return
	}

	// 从缓存获取草稿
	draftObj, exists := h.Cache.Get(req.DraftID)
	if !exists {
		Error(c, http.StatusNotFound, "Draft not found")
		return
	}

	// 创建导出器
	exporter := draft.NewExporter(h.Config)

	// 创建输出目录
	outputDir := filepath.Join("./drafts", req.DraftID)
	if err := os.MkdirAll(outputDir, 0755); err != nil {
		Error(c, http.StatusInternalServerError, fmt.Sprintf("Failed to create output directory: %v", err))
		return
	}

	// 导出草稿
	_, err := exporter.ExportDraft(draftObj, outputDir)
	if err != nil {
		Error(c, http.StatusInternalServerError, fmt.Sprintf("Failed to export draft: %v", err))
		return
	}

	// 如果配置了上传草稿，则上传到OSS
	if h.Config.IsUploadDraft {
		// TODO: 实现上传到OSS的功能
	}

	// 生成草稿URL
	draftURL := util.GenerateDraftURL(h.Config.DraftDomain, h.Config.PreviewRouter, req.DraftID)

	// 返回响应
	Success(c, SaveDraftResponse{
		DraftID:  req.DraftID,
		DraftURL: draftURL,
	})
}
